package org.cklxh.waptime;

import java.io.IOException;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.cklxh.apn.ApnPojo;

public class TimeServer {

	
	public long getWebTime(String uri,ApnPojo apnPojo)
		throws IOException{
		
		URL url = new URL(uri);
		System.out.println("正在访问："+uri);
		HttpURLConnection urlConnection;
		if(apnPojo==null){//WIFI接入
			urlConnection = (HttpURLConnection) url.openConnection();
		}else{//APN接入
			
			InetSocketAddress proxyIsa=apnPojo.getProxyIsa();
			if(proxyIsa==null){//不需要代理
				urlConnection = (HttpURLConnection) url.openConnection();
				
			}else{//需要代理
				Proxy proxy=new Proxy(java.net.Proxy.Type.HTTP,proxyIsa);
				urlConnection = (HttpURLConnection) url.openConnection(proxy);
				if(apnPojo.getProxyAi()!=null){//需要身份验证
					Authenticator.setDefault(apnPojo.getProxyAi());
				}
			}
		}
		//urlConnection.setConnectTimeout(10000);//连接延时10秒
		//Proxy proxy=new Proxy(java.net.Proxy.Type.HTTP,new InetSocketAddress("127.0.0.1",808));
		
		
		
		/*urlConnection.setConnectTimeout(10000);//连接延时20秒
		InputStream is=urlConnection.getInputStream();
		InputStreamReader isr=new InputStreamReader(is,"utf-8");
		BufferedReader br = new BufferedReader(isr);
		
		String s = "";
		StringBuffer sb = new StringBuffer();
		while ((s = br.readLine()) != null) {
			sb.append(s);
			sb.append("\r\n");
		}
		br.close();
		isr.close();
		is.close();*/
		return urlConnection.getDate();
	}
	
	
	
	public static void main(String[] args) {
		TimeServer timeServer=new TimeServer();
		long time;
		try {
			time = timeServer.getWebTime("http://wap.baidu.com/",null);
		} catch (IOException e) {
			e.printStackTrace();
			time=0;
		}
		Date date=new Date(time);
		
		String dates = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
		System.out.println(dates);
		
		
	}
}
